package com.farm.project.controller;

import com.farm.project.domain.Project;
import com.farm.project.domain.ProjectGradation;
import com.farm.project.domain.ProjectType;
import com.farm.project.service.ProjectGradationServiceInter;
import com.farm.project.service.ProjectServiceInter;
import com.farm.project.service.ProjectTypeServiceInter;
import com.farm.project.service.ProjectcompanyServiceInter;
import com.farm.project.service.ProjectuserServiceInter;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.annotation.Resource;
import com.farm.web.easyui.EasyUiUtils;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import javax.servlet.http.HttpSession;
import com.farm.core.page.RequestMode;
import com.farm.core.page.OperateType;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DBSort;
import com.farm.core.sql.query.DataQuery;
import com.farm.core.sql.result.DataResult;
import com.farm.core.page.ViewMode;
import com.farm.web.WebUtils;

/* *
 *功能：项目控制层
 *详细：
 *
 *版本：v0.1
 *作者：FarmCode代码工程
 *日期：20150707114057
 *说明：
 */
@RequestMapping("/project")
@Controller
public class ProjectController extends WebUtils {
	private final static Logger log = Logger.getLogger(ProjectController.class);
	@Resource
	private ProjectServiceInter projectServiceImpl;
	@Resource
	private ProjectTypeServiceInter projectTypeServiceImpl;
	@Resource
	private ProjectGradationServiceInter projectGradationServiceImpl;
	@Resource
	private ProjectcompanyServiceInter projectCompanyServiceImpl;
	@Resource
	private ProjectuserServiceInter projectUserServiceImpl;
	/**
	 * 查询结果集合
	 * 
	 * @return
	 */
	@RequestMapping("/query")
	@ResponseBody
	public Map<String, Object> queryall(DataQuery query, String state, HttpServletRequest request) {
		try {
			DBRule typeIdRule = query.getAndRemoveRule("TYPEID");
			if (typeIdRule != null) {
				ProjectType type = projectTypeServiceImpl.getProjecttypeEntity(typeIdRule.getValue());
				query.addRule(new DBRule("C.TREECODE", type.getTreecode(), "like-"));
			}
			if (StringUtils.isNotBlank(state)) {
				query.addRule(new DBRule("a.state", state, "="));
			}
			query = EasyUiUtils.formatGridQuery(request, query);
			query.setDefaultSort(new DBSort("a.livetime", "desc"));
			query.addRule(new DBRule("a.state", "3", "!="));
			DataResult result = projectServiceImpl.createProjectSimpleQuery(query).search();
			result.runformatTime("CTIME", "yyyy-MM-dd HH:mm");
			result.runformatTime("LIVETIME", "yyyy-MM-dd HH:mm");
			result.runDictionary("0:停用,1:激活,2:关闭,3:删除", "STATE");
			return ViewMode.getInstance().putAttrs(EasyUiUtils.formatGridData(result)).returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 提交修改数据
	 * 
	 * @return
	 */
	@RequestMapping("/edit")
	@ResponseBody
	public Map<String, Object> editSubmit(Project entity, HttpSession session) {
		// TODO 自动生成代码,修改后请去除本注释
		try {
			entity = projectServiceImpl.editProjectEntity(entity, getCurrentUser(session));
			return ViewMode.getInstance().setOperate(OperateType.UPDATE).putAttr("entity", entity).returnObjMode();

		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setOperate(OperateType.UPDATE).setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 提交新增数据
	 * 
	 * @return
	 */
	@RequestMapping("/add")
	@ResponseBody
	public Map<String, Object> addSubmit(Project entity, HttpSession session) {
		try {
			entity = projectServiceImpl.insertProjectEntity(entity, getCurrentUser(session));
			projectUserServiceImpl.resetProjectuser(entity.getId(), getCurrentUser(session));
			return ViewMode.getInstance().setOperate(OperateType.ADD).putAttr("entity", entity).returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setOperate(OperateType.ADD).setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 设置分类
	 * 
	 * @return
	 */
	@RequestMapping("/setingType")
	@ResponseBody
	public Map<String, Object> setingType(String projectIds, String typeId, HttpSession session) {
		try {
			for (String projectId : parseIds(projectIds)) {
				projectServiceImpl.editType(projectId, typeId, getCurrentUser(session));
			}
			return ViewMode.getInstance().setOperate(OperateType.ADD).returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setOperate(OperateType.ADD).setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 删除数据
	 * 
	 * @return
	 */
	@RequestMapping("/del")
	@ResponseBody
	public Map<String, Object> delSubmit(String ids, HttpSession session) {
		try {
			for (String id : parseIds(ids)) {
				projectServiceImpl.deleteProjectEntity(id, getCurrentUser(session));
			}
			return ViewMode.getInstance().returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 设置项目业务机构
	 * 
	 * @return
	 */
	@RequestMapping("/bindCompany")
	@ResponseBody
	public Map<String, Object> bindCompany(String projectids, String companyid, HttpSession session) {
		try {
			for (String projectid : parseIds(projectids)) {
				projectCompanyServiceImpl.bindProjectCompany(projectid, companyid);
			}
			return ViewMode.getInstance().returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	@RequestMapping("/list")
	public ModelAndView index(HttpSession session) {
		return ViewMode.getInstance().returnModelAndView("project/ProjectResult");
	}

	/**
	 * 显示详细信息（修改或浏览时）
	 *
	 * @return
	 */
	@RequestMapping("/form")
	public ModelAndView view(RequestMode pageset, String ids, String typeid) {
		try {
			switch (pageset.getOperateType()) {
			case (0): {// 查看
				return ViewMode.getInstance().putAttr("pageset", pageset)
						.putAttr("entity", projectServiceImpl.getProjectEntity(ids))
						.returnModelAndView("project/ProjectForm");
			}
			case (1): {// 新增
				ProjectType type = projectTypeServiceImpl.getProjecttypeEntity(typeid);
				if (type == null || !type.getModel().equals("1")) {
					return ViewMode.getInstance().putAttr("pageset", pageset)
							.setError("请选择一个有效的项目类型", new RuntimeException("请选择一个有效的项目类型"))
							.returnModelAndView("project/ProjectForm");
				}
				List<ProjectGradation> gradations = projectGradationServiceImpl.getGradationsByTypeid(type.getId());
				return ViewMode.getInstance().putAttr("pageset", pageset).putAttr("type", type)
						.putAttr("gradations", gradations).returnModelAndView("project/ProjectForm");
			}
			case (2): {// 修改
				Project project = projectServiceImpl.getProjectEntity(ids);
				ProjectType type = projectTypeServiceImpl.getProjecttypeEntity(project.getTypeid());
				List<ProjectGradation> gradations = projectGradationServiceImpl
						.getGradationsByTypeid(project.getTypeid());
				return ViewMode.getInstance().putAttr("pageset", pageset).putAttr("type", type)
						.putAttr("gradations", gradations).putAttr("entity", project)
						.returnModelAndView("project/ProjectForm");
			}
			default:
				break;
			}
			return ViewMode.getInstance().returnModelAndView("project/ProjectForm");
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e + e.getMessage(), e).returnModelAndView("project/ProjectForm");
		}
	}
}
